package com.base.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.po.voip.*;
import com.base.po.voip.fm.FmLevel;
import com.base.service.*;
import com.base.service.FM.FmLevelService;
import com.base.utils.*;
import com.beust.jcommander.internal.Lists;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.base.comm.CommContent;
import com.base.comm.CommExcel;
import com.base.helper.VosHelper;
import com.base.po.param.VosModelList;
import com.base.po.sqlparam.SubscribersExamplePage;
import com.base.po.voip.SubscribersExample.Criteria;

/**
 * admin管理系统控制器
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/admin")
public class content_yonghuguanli {
    @Autowired
    private LogsService logsService;// log日志
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private WithdrawalsService withdrawalsService;
    @Autowired
    private ShopAliOrderService shopAliOrderService;
    @Autowired
    private FreeroutesService freeroutesService;
    @Autowired
    private RewardsService rewardsService;
    @Autowired
    private PayinfoesService payinfoesService;
    @Autowired
    private CallbackinfoesService callbackinfoesService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private FmLevelService fmLevelService;

    // 用户管理
    @RequestMapping("/content_yonghuguanliOld")
    public ModelAndView indexOld(HttpServletRequest request) {
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 分页
        SubscribersExamplePage examplePage = new SubscribersExamplePage();
        examplePage.pagesize = 10;
        examplePage.start = 0;
        examplePage.rows = examplePage.pagesize;// 设置首次分页
        examplePage.setOrderByClause("CreateTime");
        Criteria criteria = examplePage.createCriteria();
        // 登录的用户ID 以及操作权限
        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        // 数据
        List<Subscribers> users = null;
        List<String> list = null; // 用户ID
        switch (adminUsergrade) {
            //  1. 判断是否是admin用户
            case 0:
                users = subscribersService.selectByExamplePage(examplePage);
                break;
            //  2. 判断是否是OEM用户
            case 1:
                list = usersService.selectByParentId(adminUserId);
                for (String oemId : list) {
                    // OEM下的商家
                    examplePage.or(examplePage.createCriteria().andParentidEqualTo(oemId));
                }
                examplePage.getOredCriteria().add(criteria.andParentidEqualTo(adminUserId));

                users = subscribersService.selectByExamplePage(examplePage);
                break;
            //  2. 判断是否是商家用户
            case 2:
                Users shop = usersService.selectByPrimaryKey(adminUserId);
                // 当前商家的上级oem
                list = usersService.selectByShopId(shop.getId());
                for (String oemId : list) {
                    // OEM下的商家
                    examplePage.or(examplePage.createCriteria().andParentidEqualTo(oemId).andShopidEqualTo(adminUserId));
                }
                examplePage.getOredCriteria()
                        .add(criteria.andParentidEqualTo(shop.getParentid()).andShopidEqualTo(adminUserId));
                // examplePage.or(examplePage.createCriteria().andShopidEqualTo(adminUserId));
                users = subscribersService.selectByExamplePage(examplePage);
                break;
        }
        /*
         * 设置分页
         */
        int totlenum = subscribersService.countByExample(examplePage);// 页面总数
        request.setAttribute("totlenum", totlenum);// 总数据传入session中
        request.setAttribute("curPage", 1);// 当前页面传入session中

        if (users != null) {
            for (Subscribers u : users) {
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());
                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());
                    u.setFreeroute(parent.getFreeroute());
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                // TODO 暂时配注
                String result = VosHelper
                        .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                if (result != null) {
                    VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                    System.out.println(v1.retCode);
                    if (v1.retCode == 0) {
                        String w = "";
                        w = v1.infoCustomers[0].getMoney().toString();
                        u.setAliaccount(w);
                    } else {
                        u.setAliaccount("暂无记录");
                    }
                }
            }
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_yonghuguanli");
            request.setAttribute("auth", 4);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("list", users);
            return modelAndView;
        }
        String usernamesys = (String) request.getSession().getAttribute("useracc");
        logsService.insert(CommContent.TYPE_SYS, CommContent.LOGS_READ + "基础用户信息", usernamesys, true,
                IP.getIpAddr(request));
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    @RequestMapping("/selectUsersOld")
    public ModelAndView selectShopOld(HttpServletRequest request, String id, String username, Integer datastatus,
                                      Integer curPage, String shopid, String parentid) {
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }
        if (id == null) {
            if (request.getSession().getAttribute("id") != null) {
                id = (String) request.getSession().getAttribute("id");
            }
        }
        if (username == null) {
            if (request.getSession().getAttribute("username") != null) {
                username = (String) request.getSession().getAttribute("username");
            }
        }
        if (shopid == null) {
            if (request.getSession().getAttribute("shopid") != null) {
                shopid = (String) request.getSession().getAttribute("shopid");
            }
        }
        if (parentid == null) {
            if (request.getSession().getAttribute("parentid") != null) {
                parentid = (String) request.getSession().getAttribute("parentid");
            }
        }
        if (datastatus == null) {
            if (request.getSession().getAttribute("datastatus") != null) {
                datastatus = (Integer) request.getSession().getAttribute("datastatus");
            } else {
                datastatus = 0;
            }
        }

        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        List<Subscribers> users = null;
        // choose = 2 默认分页查询
        Integer choose = 2;
        if (adminUsergrade < 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("")
                    || shopid != null && !shopid.equals("") || parentid != null && !parentid.equals("")
                    || datastatus != 0) {
                choose = 1;
            }
        }

        if (adminUsergrade == 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("") || datastatus != 0) {
                choose = 1;
            }
        }

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        SubscribersExamplePage examplePage = new SubscribersExamplePage();
        examplePage.setOrderByClause("CreateTime");
        examplePage.pagesize = 10;
        examplePage.start = (curPage - 1) * examplePage.pagesize;
        examplePage.rows = examplePage.pagesize;// 设置首次分页

        Criteria criteria = examplePage.createCriteria();
        if (adminUsergrade == 0) {
            // 条件筛选
            if (id != null && !id.equals("")) {
                request.setAttribute("id", id);
                criteria = criteria.andIdEqualTo(id);
                examplePage.getOredCriteria().add(criteria);
            }
            if (username != null && !username.equals("")) {
                request.setAttribute("username", username);
                criteria = criteria.andMobileLike("%" + username + "%");
                examplePage.getOredCriteria().add(criteria);
            }
            if (parentid != null && !parentid.equals("")) {
                request.setAttribute("parentid", parentid);
                criteria = criteria.andMobileLike("%" + parentid + "%");
                examplePage.getOredCriteria().add(criteria);
            }
            if (shopid != null && !shopid.equals("")) {
                request.setAttribute("shopid", shopid);
                criteria = criteria.andMobileLike("%" + shopid + "%");
                examplePage.getOredCriteria().add(criteria);
            }
            if (datastatus != null) {
                // 判断当前可用性
                switch (datastatus) {
                    case 2:
                        examplePage.getOredCriteria().add(criteria.andDatastatusEqualTo(false));
                        break;
                    case 1:
                        examplePage.getOredCriteria().add(criteria.andDatastatusEqualTo(true));
                        break;
                    case 0:
                        break;
                }
            }
        }
        if (adminUsergrade == 1) {
            List<String> list = null;
            list = usersService.selectByParentId(adminUserId);
            if (id != null && !id.equals("")) {
                request.setAttribute("id", id);
                for (String oemId : list) {
                    // OEM下的商家
                    examplePage.or(examplePage.createCriteria().andParentidEqualTo(oemId).andIdEqualTo(id));
                }
                examplePage.getOredCriteria().add(criteria.andParentidEqualTo(adminUserId).andIdEqualTo(id));

            }
            if (username != null && !username.equals("")) {
                request.setAttribute("username", username);
                for (String oemId : list) {
                    // OEM下的商家
                    examplePage.or(
                            examplePage.createCriteria().andParentidEqualTo(oemId).andMobileLike("%" + username + "%"));
                }
                examplePage.getOredCriteria()
                        .add(criteria.andParentidEqualTo(adminUserId).andMobileLike("%" + username + "%"));
            }
            if (parentid != null && !parentid.equals("")) {
                request.setAttribute("parentid", parentid);
                Users agent = usersService.selectByUsername(parentid.trim());
                if (agent != null) {

                    examplePage.getOredCriteria().add(criteria.andParentidEqualTo(agent.getId()));
                }
            }

            if (shopid != null && !shopid.equals("")) {
                request.setAttribute("shopid", shopid);
                Users shop = usersService.selectByUsername(shopid.trim());
                if (shop != null) {

                    examplePage.getOredCriteria().add(criteria.andShopidEqualTo(shop.getId()));
                }
            }
            if (datastatus != null) {
                // 判断当前可用性
                switch (datastatus) {
                    case 2:
                        for (String oemId : list) {
                            // 遍歷所有oem下的用戶
                            examplePage
                                    .or(examplePage.createCriteria().andParentidEqualTo(oemId).andDatastatusEqualTo(false));
                        }
                        examplePage.or(
                                examplePage.createCriteria().andParentidEqualTo(adminUserId).andDatastatusEqualTo(false));
                        break;
                    case 1:
                        for (String oemId : list) {
                            // 遍歷所有oem下的用戶
                            examplePage
                                    .or(examplePage.createCriteria().andParentidEqualTo(oemId).andDatastatusEqualTo(true));
                        }
                        examplePage.or(
                                examplePage.createCriteria().andParentidEqualTo(adminUserId).andDatastatusEqualTo(true));
                        break;
                    case 0:
                        break;
                }
            }
        }
        if (adminUsergrade == 2) {
            List<String> list = null;
            // 当前商家
            Users shop = usersService.selectByPrimaryKey(adminUserId);
            // 当前商家的上级oem
            list = usersService.selectByShopId(shop.getId());
            if (id != null && !id.equals("")) {
                request.setAttribute("id", id);
                for (String oemId : list) {
                    // OEM下的商家
                    examplePage
                            .or(examplePage.createCriteria().andParentidEqualTo(oemId).andShopidEqualTo(adminUserId));
                }
                examplePage.getOredCriteria()
                        .add(criteria.andParentidEqualTo(shop.getParentid()).andShopidEqualTo(adminUserId));
            }
            if (username != null && !username.equals("")) {
                request.setAttribute("username", username);
                for (String oemId : list) {
                    examplePage.or(examplePage.createCriteria().andParentidEqualTo(oemId)
                            .andMobileLike("%" + username + "%").andShopidEqualTo(adminUserId));
                }
                examplePage.getOredCriteria()
                        .add(criteria.andParentidEqualTo(shop.getParentid()).andMobileLike("%" + username + "%")
                                .andShopidEqualTo(adminUserId));
            }
            if (datastatus != null) {
                // 判断当前可用性
                switch (datastatus) {
                    case 2:
                        for (String oemId : list) {
                            examplePage
                                    .or(examplePage.createCriteria().andParentidEqualTo(oemId).andDatastatusEqualTo(false));
                        }
                        examplePage.getOredCriteria()
                                .add(criteria.andParentidEqualTo(shop.getParentid()).andDatastatusEqualTo(false));
                        break;
                    case 1:
                        for (String oemId : list) {
                            examplePage
                                    .or(examplePage.createCriteria().andParentidEqualTo(oemId).andDatastatusEqualTo(true));
                        }
                        examplePage.getOredCriteria()
                                .add(criteria.andParentidEqualTo(shop.getParentid()).andDatastatusEqualTo(true));
                        break;
                    case 0:
                        break;
                }
            }
        }

        request.setAttribute("datastatus", datastatus);
        if (choose == 2) {
            List<String> list = null;
            switch (adminUsergrade) {
                //  1. 判断是否是admin用户
                case 0:
                    users = subscribersService.selectByExamplePage(examplePage);
                    break;
                //  2. 判断是否是OEM用户
                case 1:
                    list = usersService.selectByParentId(adminUserId);
                    for (String oemId : list) {
                        // OEM下的商家
                        examplePage.or(examplePage.createCriteria().andParentidEqualTo(oemId));
                    }
                    examplePage.getOredCriteria().add(criteria.andParentidEqualTo(adminUserId));

                    users = subscribersService.selectByExamplePage(examplePage);
                    break;
                //  2. 判断是否是商家用户
                case 2:
                    // 查詢该商家用戶下的所有的商家 users 集合
                    Users shop = usersService.selectByPrimaryKey(adminUserId);
                    // 当前商家的上级oem
                    list = usersService.selectByShopId(shop.getId());
                    for (String oemId : list) {
                        // OEM下的商家
                        examplePage
                                .or(examplePage.createCriteria().andParentidEqualTo(oemId).andShopidEqualTo(adminUserId));
                    }
                    examplePage.getOredCriteria()
                            .add(criteria.andParentidEqualTo(shop.getParentid()).andShopidEqualTo(adminUserId));
                    users = subscribersService.selectByExamplePage(examplePage);
                    break;
            }
        }
        users = subscribersService.selectByExamplePage(examplePage);
        /*
         * 设置分页
         */
        int totlenum = subscribersService.countByExample(examplePage);// 页面总数
        request.setAttribute("totlenum", totlenum);// 总数据传入session中
        request.setAttribute("curPage", curPage);// 当前页面传入session中

        users = subscribersService.selectByExamplePage(examplePage);
        if (users != null) {
            for (Subscribers u : users) {
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());

                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());
                    u.setFreeroute(parent.getFreeroute());
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }

                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                // TODO 暂时配注
                String result = VosHelper
                        .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                if (result != null) {
                    VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                    System.out.println(v1.retCode);
                    if (v1.retCode == 0) {
                        String w = "";
                        w = v1.infoCustomers[0].getMoney().toString();
                        u.setAliaccount(w);
                    } else {
                        u.setAliaccount("暂无记录");
                    }
                }
            }
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_yonghuguanli");
            request.setAttribute("auth", datastatus);
            request.setAttribute("list", users);
            return modelAndView;
        }
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }


    @RequestMapping("/content_yonghuguanli")
    public ModelAndView index(HttpServletRequest request) throws Exception {
        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        Page page = new Page();
        // 登录的用户ID 以及操作权限
        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        String userNick = (String) request.getSession().getAttribute("userNick");
        // 数据
        List<Subscribers> users = null;
        switch (adminUsergrade) {
            //  1. 判断是否是admin用户
            case 0:
                page.setCurrentPageNo(1);
                page.setRecordTotal(subscribersService.countByAll(null, null, null, null, null, null, null, null, null, null));
                users = subscribersService.selectByAll(page, null, null, null, null, null, null, null, null, null, null);
                break;
            //  2. 判断是否是OEM用户
            case 1:
                page.setCurrentPageNo(1);
                page.setRecordTotal(subscribersService.countByParentid(adminUserId, null, null, null, null, null, null, null, null, null, null));
                users = subscribersService.selectByParentid(page, adminUserId, null, null, null, null, null, null, null, null, null, null);
                break;
            //  2. 判断是否是商家用户
            case 2:
                page.setCurrentPageNo(1);
                page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, null, null, null, null, null, null, null, null, null));
                users = subscribersService.selectByShopidNotAll(page, adminUserId, null, null, null, null, null, null, null, null, null);
                break;
        }
        /*
         * 设置分页
         */
        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中
        if (users != null) {
            for (Subscribers u : users) {
                String pId = u.getParentid();
                u.setPassword(u.getPassword() == null || u.getPassword().isEmpty() ? "未设置" : PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                //纪录用户打电话的总消耗
                String mobile=u.getMobile();
               Long mob= Long.parseLong(mobile);
                Map<String,Object> mp=callbackinfoesService.sumOmentyByMobile(mob.toString(),pId);
                Double money=0.0; //话费
                Double OMoney=0.0;//线路消耗
                if(mp!=null){
                    if(mp.get("ommoney")!=null){
                        OMoney=Double.parseDouble(mp.get("ommoney").toString());
                    }
                    if(mp.get("money")!=null){
                        money=Double.parseDouble(mp.get("money").toString());
                    }
                }
                u.setOMoney(OMoney);
                u.setMoneyxiaofei(money);
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());
                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());

                    if (parent.getId().equals("d34f8cb561bd48a992556f4faed45e2d")) {
                        if (parent.getFreeroute().equals("随便打")) {
                            u.setFreeroute("SBD0.25");
                        }
                    } else {
                        u.setFreeroute(parent.getFreeroute());
                    }
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

                //积分计算
                Subscribers sub = subscribersService.selectByPrimaryKey(u.getId()); // 用户信息
                // 计算用户已经消费积分
                float all = 0f; // 用户订单总返现积分
                float consume = withdrawalsService.countByAlready(sub.getId(), 1, null); // 用户已经消费积分
                float ctIntegral = 0f; // 当前用户剩余总积分
                List<ShopAliOrder> shopAliOrder = shopAliOrderService.selectByAll(sub.getId(), 1, 2); // 阿里订单集合
                // 判断用户是否有阿里订单 结算积分
                if (shopAliOrder != null && shopAliOrder.size() != 0) {
                    float aliSingle = 0f; // 单个阿里订单返现积分
                    // 商家积分计算类型为1 积分万分之五
                    if (usersService.selectByPrimaryKey(sub.getShopid()).getIgtype() == 1) {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 结算金额
                            float jsmoney = s.getJsmoney().floatValue();
                            // 单个阿里订单已经返现积分 = 结算金额 * 天数 （天数 = 当前时间 - 创建时间）* 万分之五
                            aliSingle = jsmoney * Produce.differentDays(s.getClicktime(), Produce.getNowDate())
                                    * 0.0005f;
                            // 如果单个阿里订单返现积分大于结算金额 则积分 = 结算金额
                            if (aliSingle > jsmoney)
                                aliSingle = jsmoney;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                    // 类型为2 积分15%
                    else {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 单个订单返现积分 = 结算金额 * 15%
                            aliSingle = s.getJsmoney().floatValue() * 0.15f;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                }
                // ======未结算京东积分======
                // 判断用户是否有京东订单 结算积分
                // ======all+=京东积分======
                ctIntegral = all - consume; // 当前用户总积分 = 订单总积分 - 已经消费积分
                if (ctIntegral < 0f) {
                    ctIntegral = 0f;
                }
                // 积分
                u.setIntegral(ctIntegral);
                if (u.getIntegral() == null) {
                    u.setIntegral(0f);
                }
                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                DecimalFormat df = new DecimalFormat("#0.00");
                // TODO 暂时配注
                try {
                    // TODO 暂时配注
                    String result = VosHelper
                            .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                    if (result != null) {
                        VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                        System.out.println(v1.retCode);
                        if (v1.retCode == 0) {
                            String w = "";
                            w = df.format(v1.infoCustomers[0].getMoney());
                            u.setAliaccount(w);
                            Date time = new Date(v1.infoCustomers[0].getValidTime());
                            u.setEndtime(time);
                        } else {
                            u.setAliaccount("暂无记录");
                        }
                    }
                } catch (Exception e) {
                    u.setAliaccount("暂无记录");
                }

                int shareSubs1 = rewardsService.countByAllLevel1(u.getId());
                int shareSubs2 = rewardsService.countByAllLevel2(u.getId());
                int shareSubs3 = rewardsService.countByAllLevel3(u.getId());
                int level1 = 0;
                if (shareSubs1 < 3){
                    level1 = 0;
                }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                    level1 = 1;
                }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                    level1 = 2;
                }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                    level1 = 3;
                }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                    level1 = 4;
                }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                    level1 = 5;
                }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                    level1 = 6;
                }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                    level1 = 7;
                }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                    level1 = 8;
                }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                    level1 = 9;
                }
                if (u.getCbonus1level() != 0 && u.getCbonus1level() > level1){
                    level1 = u.getCbonus1level();
                }
                if (level1 == 0){
                    u.setAchlevel1("无等级");
                }else {
                    u.setAchlevel1("T" + level1);
                }

                BigDecimal shareNum = payinfoesService.selectAllPerformance(u.getId(), 1).subtract(new BigDecimal(u.getAchievement1()));
                BigDecimal shareNum2 = payinfoesService.selectAllPerformance(u.getId(), 2).subtract(new BigDecimal(u.getAchievement2()));
                BigDecimal shareNum3 = payinfoesService.selectAllPerformance(u.getId(), 3).subtract(new BigDecimal(u.getAchievement3()));
                u.setAchlevel1Num(shareNum);
                u.setAchlevel2Num(shareNum2);
                u.setAchlevel3Num(shareNum3);

                float ig = 0f;
                List<Rewards> rewardsList = rewardsService.selectByPhase(pId, u.getId());
                if (rewardsList != null && rewardsList.size() > 0){
                    Rewards rewards = rewardsList.get(0);
                    ig = rewards.getIntegral().floatValue();
                }
                float igw = 0f;
                List<Rewards> igwList = rewardsService.selectByWithdraw(pId, u.getId());
                if (igwList != null && igwList.size() > 0){
                    Rewards rewards = igwList.get(0);
                    igw = rewards.getIntegral().floatValue();
                }
                float integral = rewardsService.countByIntegral(pId, u.getId())
                        + rewardsService.countByBonus(pId, u.getId())
                        + rewardsService.countByExtra(pId, u.getId())
                        + rewardsService.countBySelfShop(pId, u.getId())
                        + rewardsService.countByRefund(pId, u.getId())
                        - ig
                        - (withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f - igw);
                u.setIgrewardAll(integral);
                u.setWithdrawalsAll((withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f) - igw);
            }

            //费率
            FreeroutesExample freeroutesExample = new FreeroutesExample();
            freeroutesExample.setOrderByClause("CreateTime");
            freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
            List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);

            Users user = usersService.selectByPrimaryKey(adminUserId);
            Users pUser = null;
            if (adminUsergrade != 0){
                pUser = usersService.selectByPrimaryKey(user.getParentid());
            }
            /**
             *  @Date: 2020/4/20 14:48
             *  @Description:
             *  富美专用逻辑
             */
            if (adminUserId.equals("a6b818fa0a4b4b7c97da4bff24ff1d6a")){
                users.forEach(item->{
                  Subscribers subscribers=subscribersService.selectByPrimaryKey(item.getId());
                    FmLevel fmLevel=null;
                  if (subscribers!=null){
                       fmLevel=  fmLevelService.selectBySubId(subscribers.getId());
                  }
                    item.setRole(fmLevel==null?0:fmLevel.getSublevel());
                });

            }
            // 设置页面进行跳转
            CommExcel.subscribersList.clear();
            modelAndView.setViewName("jsp/content_yonghuguanli");
            request.setAttribute("list", users);
            request.setAttribute("datastatus", 0);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("adminUserId", adminUserId);
            request.setAttribute("userNick", userNick);
            request.setAttribute("freeroutes", freeroutes);
            return modelAndView;
        }
        String usernamesys = (String) request.getSession().getAttribute("useracc");
        logsService.insert(CommContent.TYPE_SYS, CommContent.LOGS_READ + "基础用户信息", usernamesys, true,
                IP.getIpAddr(request));
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    @RequestMapping("content_dailiguanli")
    @ApiOperation("查询一级代理")
    public ModelAndView selectDaili(HttpServletRequest request,Integer curPage){
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }
        Page page = new Page(curPage);
        page.setRecordTotal(subscribersService.countByMenber());
        List<Daili> list = subscribersService.selectDaili(page);
        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中
        request.setAttribute("list", list);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("jsp/content_dailiguanli");
        return modelAndView;
    }


    @RequestMapping("/selectUsers")
    public ModelAndView selectUsers(HttpServletRequest request, String id, String username, Integer datastatus,
                                    Integer curPage, String shopid, String parentid, String startTimeFrom, String name,
                                    String startTimeTo, String endTimeFrom, String endTimeTo) {
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }
        if (id == null) {
            if (request.getSession().getAttribute("id") != null) {
                id = (String) request.getSession().getAttribute("id");
            }
        }
        if (username == null) {
            if (request.getSession().getAttribute("username") != null) {
                username = (String) request.getSession().getAttribute("username");
            }
        }
        if (shopid == null) {
            if (request.getSession().getAttribute("shopid") != null) {
                shopid = (String) request.getSession().getAttribute("shopid");
            }
        }
        if (parentid == null) {
            if (request.getSession().getAttribute("parentid") != null) {
                parentid = (String) request.getSession().getAttribute("parentid");
            }
        }
        if (datastatus == null) {
            if (request.getSession().getAttribute("datastatus") != null) {
                datastatus = (Integer) request.getSession().getAttribute("datastatus");
            } else {
                datastatus = 0;
            }
        }
        if (parentid == null || parentid.equals("") || parentid.equals("undefined")) {
            parentid = null;
        }
        if (shopid == null || shopid.equals("") || shopid.equals("undefined")) {
            shopid = null;
        }
        if (name == null || name.equals("") || name.equals("undefined")) {
            name = null;
        }

        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        String userNick = (String) request.getSession().getAttribute("userNick");
        List<Subscribers> users = null;
        // choose = 2 默认分页查询
        Integer choose = 2;
        if (adminUsergrade < 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("")
                    || shopid != null && !shopid.equals("") || parentid != null && !parentid.equals("")
                    || datastatus != 0 || startTimeFrom != null && !startTimeFrom.equals("")
                    && startTimeTo != null && !startTimeTo.equals("") || endTimeFrom != null
                    && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        if (adminUsergrade == 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("") || datastatus != 0
                    || startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null
                    && !startTimeTo.equals("") || endTimeFrom != null && !endTimeFrom.equals("")
                    && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();

        //oem查询或者商家查询
        String pName = null;
        String sName = null;
        String mobile = null;
        String sUserName = null;
        Boolean status = null;
        String sStartTimeFrom = null;
        String sStartTimeTo = null;
        String sEndTimeFrom = null;
        String sEndTimeTo = null;
        Users us = null;
        Page page = new Page();
        if (adminUsergrade == 0 || adminUsergrade == 1) {
            if (parentid != null && !parentid.equals("") && !parentid.equals("undefined")) {
//				us =usersService.selectByUsername(parentid);
//				pName = us.getId();
                pName = parentid;
            }
            if (shopid != null && !shopid.equals("") && !shopid.equals("undefined")) {
//				us =usersService.selectByUsername(shopid);
//				sName = us.getId();
                sName = shopid;
            }
        }
        if (username != null && !username.equals("")) {
            mobile = username;
        }
        if (name != null && !name.equals("")) {
            sUserName = name;
        }
        if (startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null && !startTimeTo.equals("")) {
            sStartTimeFrom = startTimeFrom;
            sStartTimeTo = startTimeTo;
        }
        if (endTimeFrom != null && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")) {
            sEndTimeFrom = endTimeFrom;
            sEndTimeTo = endTimeTo;
        }
        if (datastatus != null) {
            // 判断当前可用性
            switch (datastatus) {
                case 2:
                    status = false;
                    break;
                case 1:
                    status = true;
                    break;
                case 0:
                    break;
            }
        }
        page.setCurrentPageNo(curPage);
        if (adminUsergrade == 0) {
            page.setRecordTotal(subscribersService.countByAll(null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByAll(page, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (adminUsergrade == 1) {
            page.setRecordTotal(subscribersService.countByParentid(adminUserId, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByParentid(page, adminUserId, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (adminUsergrade == 2) {
            page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, null, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByShopidNotAll(page, adminUserId, null, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }
        if (choose == 2) {
            switch (adminUsergrade) {
                //  1. 判断是否是admin用户
                case 0:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByAll(null, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByAll(page, null, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是OEM用户
                case 1:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByParentid(adminUserId, null, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByParentid(page, adminUserId, null, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是商家用户
                case 2:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByShopidNotAll(page, adminUserId, null, null, null, null, null, null, null, null, null);
                    break;
            }
        }

        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

        if (users != null) {
            for (Subscribers u : users) {
                String pId = u.getParentid();
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());
                //纪录用户打电话的总消耗
                String mobile1=u.getMobile();
                Long mob= Long.parseLong(mobile1);
                Map<String,Object> mp=callbackinfoesService.sumOmentyByMobile(mob.toString(),pId);
                Double money=0.0;
                Double OMoney=0.0;
                if(mp!=null){
                    if(mp.get("ommoney")!=null){
                        OMoney=Double.parseDouble(mp.get("ommoney").toString());
                    }
                    if(mp.get("money")!=null){
                        money=Double.parseDouble(mp.get("money").toString());
                    }
                }
                u.setOMoney(OMoney);
                u.setMoneyxiaofei(money);
                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());

                    if (parent.getId().equals("d34f8cb561bd48a992556f4faed45e2d")) {
                        if (parent.getFreeroute().equals("随便打")) {
                            u.setFreeroute("SBD0.25");
                        }
                    } else {
                        u.setFreeroute(parent.getFreeroute());
                    }
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

//				Subscribers sub = subscribersService.selectByPrimaryKey(u.getId()); // 用户信息
                // 计算用户已经消费积分
                float all = 0f; // 用户订单总返现积分
                float consume = withdrawalsService.countByAlready(u.getId(), 1, null); // 用户已经消费积分
                float ctIntegral = 0f; // 当前用户剩余总积分
                List<ShopAliOrder> shopAliOrder = shopAliOrderService.selectByAll(u.getId(), 1, 2); // 阿里订单集合
                // 判断用户是否有阿里订单 结算积分
                if (shopAliOrder != null && shopAliOrder.size() != 0) {
                    float aliSingle = 0f; // 单个阿里订单返现积分
                    // 商家积分计算类型为1 积分万分之五
                    if (usersService.selectByPrimaryKey(u.getShopid()).getIgtype() == 1) {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 结算金额
                            float jsmoney = s.getJsmoney().floatValue();
                            // 单个阿里订单已经返现积分 = 结算金额 * 天数 （天数 = 当前时间 - 创建时间）* 万分之五
                            aliSingle = jsmoney * Produce.differentDays(s.getClicktime(), Produce.getNowDate())
                                    * 0.0005f;
                            // 如果单个阿里订单返现积分大于结算金额 则积分 = 结算金额
                            if (aliSingle > jsmoney)
                                aliSingle = jsmoney;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                    // 类型为2 积分15%
                    else {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 单个订单返现积分 = 结算金额 * 15%
                            aliSingle = s.getJsmoney().floatValue() * 0.15f;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                }
                // ======未结算京东积分======
                // 判断用户是否有京东订单 结算积分
                // ======all+=京东积分======
                ctIntegral = all - consume; // 当前用户总积分 = 订单总积分 - 已经消费积分
                if (ctIntegral < 0f) {
                    ctIntegral = 0f;
                }
                // 积分
                u.setIntegral(ctIntegral);
                if (u.getIntegral() == null) {
                    u.setIntegral(0f);
                }
                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                DecimalFormat df = new DecimalFormat("#0.00");
                try {
                    // TODO 暂时配注
                    String result = VosHelper
                            .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                    if (result != null) {
                        VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                        System.out.println(v1.retCode);
                        if (v1.retCode == 0) {
                            String w = "";
                            w = df.format(v1.infoCustomers[0].getMoney());
                            u.setAliaccount(w);
                            Date time = new Date(v1.infoCustomers[0].getValidTime());
                            u.setEndtime(time);
                        } else {
                            u.setAliaccount("暂无记录");
                        }
                    }
                } catch (Exception e) {
                    u.setAliaccount("暂无记录");
                }

                int shareSubs1 = rewardsService.countByAllLevel1(u.getId());
                int shareSubs2 = rewardsService.countByAllLevel2(u.getId());
                int shareSubs3 = rewardsService.countByAllLevel3(u.getId());
                int level1 = 0;
                if (shareSubs1 < 3){
                    level1 = 0;
                }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                    level1 = 1;
                }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                    level1 = 2;
                }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                    level1 = 3;
                }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                    level1 = 4;
                }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                    level1 = 5;
                }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                    level1 = 6;
                }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                    level1 = 7;
                }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                    level1 = 8;
                }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                    level1 = 9;
                }
                if (u.getCbonus1level() != 0 && u.getCbonus1level() > level1){
                    level1 = u.getCbonus1level();
                }
                if (level1 == 0){
                    u.setAchlevel1("无等级");
                }else {
                    u.setAchlevel1("T" + level1);
                }

                BigDecimal shareNum = payinfoesService.selectAllPerformance(u.getId(), 1).subtract(new BigDecimal(u.getAchievement1()));
                BigDecimal shareNum2 = payinfoesService.selectAllPerformance(u.getId(), 2).subtract(new BigDecimal(u.getAchievement2()));
                BigDecimal shareNum3 = payinfoesService.selectAllPerformance(u.getId(), 3).subtract(new BigDecimal(u.getAchievement3()));
                u.setAchlevel1Num(shareNum);
                u.setAchlevel2Num(shareNum2);
                u.setAchlevel3Num(shareNum3);

                float ig = 0f;
                List<Rewards> rewardsList = rewardsService.selectByPhase(pId, u.getId());
                if (rewardsList != null && rewardsList.size() > 0){
                    Rewards rewards = rewardsList.get(0);
                    ig = rewards.getIntegral().floatValue();
                }
                float igw = 0f;
                List<Rewards> igwList = rewardsService.selectByWithdraw(pId, u.getId());
                if (igwList != null && igwList.size() > 0){
                    Rewards rewards = igwList.get(0);
                    igw = rewards.getIntegral().floatValue();
                }
                float integral = rewardsService.countByIntegral(pId, u.getId())
                        + rewardsService.countByBonus(pId, u.getId())
                        + rewardsService.countByExtra(pId, u.getId())
                        + rewardsService.countBySelfShop(pId, u.getId())
                        + rewardsService.countByRefund(pId, u.getId())
                        - ig
                        - (withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f - igw);
                u.setIgrewardAll(integral);
                u.setWithdrawalsAll((withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f) - igw);
            }

            //费率
            FreeroutesExample freeroutesExample = new FreeroutesExample();
            freeroutesExample.setOrderByClause("CreateTime");
            freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
            List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);

            Users user = usersService.selectByPrimaryKey(adminUserId);
            Users pUser = null;
            if (adminUsergrade != 0){
                pUser = usersService.selectByPrimaryKey(user.getParentid());
            }

            CommExcel.subscribersList.clear();
            /**
             *  @Date: 2020/4/20 14:48
             *  @Description:
             *  富美专用逻辑
             */
            if (adminUserId.equals("a6b818fa0a4b4b7c97da4bff24ff1d6a")){
                users.forEach(item->{
                    Subscribers subscribers=subscribersService.selectByPrimaryKey(item.getId
                            ());
                    FmLevel fmLevel=null;
                    if (subscribers!=null){
                        fmLevel=  fmLevelService.selectBySubId(subscribers.getId());
                    }
                    item.setRole(fmLevel==null?0:fmLevel.getSublevel());
                });

            }
            //todo
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_yonghuguanli");
            request.setAttribute("list", users);
            request.setAttribute("username", username);
            request.setAttribute("name", name);
            request.setAttribute("parentid", parentid);
            request.setAttribute("shopid", shopid);
            request.setAttribute("datastatus", datastatus);
            request.setAttribute("startTimeFrom", startTimeFrom);
            request.setAttribute("startTimeTo", startTimeTo);
            request.setAttribute("endTimeFrom", endTimeFrom);
            request.setAttribute("endTimeTo", endTimeTo);
            request.setAttribute("adminUserId", adminUserId);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("freeroutes", freeroutes);
            request.setAttribute("userNick", userNick);
            return modelAndView;
        }
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    // 下级商家用户
    @RequestMapping("/selectShopUsers")
    public ModelAndView selectShopUsers(HttpServletRequest request, String pid,
                                        String id, String username, Integer datastatus, String name,
                                        Integer curPage, String shopid, String parentid, String startTimeFrom,
                                        String startTimeTo, String endTimeFrom, String endTimeTo) {
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }
        if (id == null) {
            if (request.getSession().getAttribute("id") != null) {
                id = (String) request.getSession().getAttribute("id");
            }
        }
        if (username == null) {
            if (request.getSession().getAttribute("username") != null) {
                username = (String) request.getSession().getAttribute("username");
            }
        }
        if (shopid == null) {
            if (request.getSession().getAttribute("shopid") != null) {
                shopid = (String) request.getSession().getAttribute("shopid");
            }
        }
        if (parentid == null) {
            if (request.getSession().getAttribute("parentid") != null) {
                parentid = (String) request.getSession().getAttribute("parentid");
            }
        }
        if (datastatus == null) {
            if (request.getSession().getAttribute("datastatus") != null) {
                datastatus = (Integer) request.getSession().getAttribute("datastatus");
            } else {
                datastatus = 0;
            }
        }
        if (parentid == null || parentid.equals("undefined")) {
            parentid = null;
        }
        if (shopid == null || shopid.equals("undefined")) {
            shopid = null;
        }

        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String userNick = (String) request.getSession().getAttribute("userNick");
        Integer pGrade = 2;
        String adminUserId = pid;
        List<Subscribers> users = null;
        // choose = 2 默认分页查询
        Integer choose = 2;
        if (adminUsergrade < 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("")
                    || shopid != null && !shopid.equals("") || parentid != null && !parentid.equals("")
                    || datastatus != 0 || startTimeFrom != null && !startTimeFrom.equals("")
                    && startTimeTo != null && !startTimeTo.equals("") || endTimeFrom != null
                    && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        if (adminUsergrade == 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("") || datastatus != 0
                    || startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null
                    && !startTimeTo.equals("") || endTimeFrom != null && !endTimeFrom.equals("")
                    && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();

        //oem查询或者商家查询
        String pName = null;
        String sName = null;
        String mobile = null;
        String sUserName = null;
        Boolean status = null;
        String sStartTimeFrom = null;
        String sStartTimeTo = null;
        String sEndTimeFrom = null;
        String sEndTimeTo = null;
        Users us = null;
        Page page = new Page();
        if (adminUsergrade == 0 || adminUsergrade == 1) {
            if (parentid != null && !parentid.equals("") && !parentid.equals("undefined")) {
//				us =usersService.selectByUsername(parentid);
//				pName = us.getId();
                pName = parentid;
            }
            if (shopid != null && !shopid.equals("") && !shopid.equals("undefined")) {
//				us =usersService.selectByUsername(shopid);
//				sName = us.getId();
                sName = shopid;
            }
        }
        if (username != null && !username.equals("")) {
            mobile = username;
        }
        if (name != null && !name.equals("")) {
            sUserName = name;
        }
        if (startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null && !startTimeTo.equals("")) {
            sStartTimeFrom = startTimeFrom;
            sStartTimeTo = startTimeTo;
        }
        if (endTimeFrom != null && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")) {
            sEndTimeFrom = endTimeFrom;
            sEndTimeTo = endTimeTo;
        }
        if (datastatus != null) {
            // 判断当前可用性
            switch (datastatus) {
                case 2:
                    status = false;
                    break;
                case 1:
                    status = true;
                    break;
                case 0:
                    break;
            }
        }
        page.setCurrentPageNo(curPage);
        if (pGrade == 0) {
            page.setRecordTotal(subscribersService.countByAll(null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByAll(page, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (pGrade == 1) {
            page.setRecordTotal(subscribersService.countByParentid(adminUserId, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByParentid(page, adminUserId, null, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (pGrade == 2) {
            page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, null, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByShopidNotAll(page, adminUserId, null, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }
        if (choose == 2) {
            switch (pGrade) {
                //  1. 判断是否是admin用户
                case 0:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByAll(null, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByAll(page, null, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是OEM用户
                case 1:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByParentid(adminUserId, null, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByParentid(page, adminUserId, null, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是商家用户
                case 2:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByShopidNotAll(page, adminUserId, null, null, null, null, null, null, null, null, null);
                    break;
            }
        }

        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

        if (users != null) {
            for (Subscribers u : users) {
                String pId = u.getParentid();
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());

                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());

                    if (parent.getId().equals("d34f8cb561bd48a992556f4faed45e2d")) {
                        if (parent.getFreeroute().equals("随便打")) {
                            u.setFreeroute("SBD0.25");
                        }
                    } else {
                        u.setFreeroute(parent.getFreeroute());
                    }
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

//				Subscribers sub = subscribersService.selectByPrimaryKey(u.getId()); // 用户信息
                // 计算用户已经消费积分
                float all = 0f; // 用户订单总返现积分
                float consume = withdrawalsService.countByAlready(u.getId(), 1, null); // 用户已经消费积分
                float ctIntegral = 0f; // 当前用户剩余总积分
                List<ShopAliOrder> shopAliOrder = shopAliOrderService.selectByAll(u.getId(), 1, 2); // 阿里订单集合
                // 判断用户是否有阿里订单 结算积分
                if (shopAliOrder != null && shopAliOrder.size() != 0) {
                    float aliSingle = 0f; // 单个阿里订单返现积分
                    // 商家积分计算类型为1 积分万分之五
                    if (usersService.selectByPrimaryKey(u.getShopid()).getIgtype() == 1) {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 结算金额
                            float jsmoney = s.getJsmoney().floatValue();
                            // 单个阿里订单已经返现积分 = 结算金额 * 天数 （天数 = 当前时间 - 创建时间）* 万分之五
                            aliSingle = jsmoney * Produce.differentDays(s.getClicktime(), Produce.getNowDate())
                                    * 0.0005f;
                            // 如果单个阿里订单返现积分大于结算金额 则积分 = 结算金额
                            if (aliSingle > jsmoney)
                                aliSingle = jsmoney;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                    // 类型为2 积分15%
                    else {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 单个订单返现积分 = 结算金额 * 15%
                            aliSingle = s.getJsmoney().floatValue() * 0.15f;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                }
                // ======未结算京东积分======
                // 判断用户是否有京东订单 结算积分
                // ======all+=京东积分======
                ctIntegral = all - consume; // 当前用户总积分 = 订单总积分 - 已经消费积分
                if (ctIntegral < 0f) {
                    ctIntegral = 0f;
                }
                // 积分
                u.setIntegral(ctIntegral);
                if (u.getIntegral() == null) {
                    u.setIntegral(0f);
                }
                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                DecimalFormat df = new DecimalFormat("#0.00");
                try {
                    // TODO 暂时配注
                    String result = VosHelper
                            .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                    if (result != null) {
                        VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                        System.out.println(v1.retCode);
                        if (v1.retCode == 0) {
                            String w = "";
                            w = df.format(v1.infoCustomers[0].getMoney());
//							w = v1.infoCustomers[0].getMoney().toString();
                            u.setAliaccount(w);
                        } else {
                            u.setAliaccount("暂无记录");
                        }
                    }
                } catch (Exception e) {
                    u.setAliaccount("暂无记录");
                }

                int shareSubs1 = rewardsService.countByAllLevel1(u.getId());
                int shareSubs2 = rewardsService.countByAllLevel2(u.getId());
                int shareSubs3 = rewardsService.countByAllLevel3(u.getId());
                int level1 = 0;
                if (shareSubs1 < 3){
                    level1 = 0;
                }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                    level1 = 1;
                }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                    level1 = 2;
                }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                    level1 = 3;
                }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                    level1 = 4;
                }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                    level1 = 5;
                }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                    level1 = 6;
                }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                    level1 = 7;
                }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                    level1 = 8;
                }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                    level1 = 9;
                }
                if (u.getCbonus1level() != 0 && u.getCbonus1level() > level1){
                    level1 = u.getCbonus1level();
                }
                if (level1 == 0){
                    u.setAchlevel1("无等级");
                }else {
                    u.setAchlevel1("T" + level1);
                }

                BigDecimal shareNum = payinfoesService.selectAllPerformance(u.getId(), 1).subtract(new BigDecimal(u.getAchievement1()));
                BigDecimal shareNum2 = payinfoesService.selectAllPerformance(u.getId(), 2).subtract(new BigDecimal(u.getAchievement2()));
                BigDecimal shareNum3 = payinfoesService.selectAllPerformance(u.getId(), 3).subtract(new BigDecimal(u.getAchievement3()));
                u.setAchlevel1Num(shareNum);
                u.setAchlevel2Num(shareNum2);
                u.setAchlevel3Num(shareNum3);

                float ig = 0f;
                List<Rewards> rewardsList = rewardsService.selectByPhase(pId, u.getId());
                if (rewardsList != null && rewardsList.size() > 0){
                    Rewards rewards = rewardsList.get(0);
                    ig = rewards.getIntegral().floatValue();
                }
                float igw = 0f;
                List<Rewards> igwList = rewardsService.selectByWithdraw(pId, u.getId());
                if (igwList != null && igwList.size() > 0){
                    Rewards rewards = igwList.get(0);
                    igw = rewards.getIntegral().floatValue();
                }
                float integral = rewardsService.countByIntegral(pId, u.getId())
                        + rewardsService.countByBonus(pId, u.getId())
                        + rewardsService.countByExtra(pId, u.getId())
                        + rewardsService.countBySelfShop(pId, u.getId())
                        + rewardsService.countByRefund(pId, u.getId())
                        - ig
                        - (withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f - igw);
                u.setIgrewardAll(integral);
                u.setWithdrawalsAll((withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f) - igw);
            }

            //费率
            FreeroutesExample freeroutesExample = new FreeroutesExample();
            freeroutesExample.setOrderByClause("CreateTime");
            freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
            List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);

            Users user = usersService.selectByPrimaryKey(adminUserId);
            Users pUser = usersService.selectByPrimaryKey(user.getParentid());

            CommExcel.subscribersList.clear();
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_shangjiayonghuguanli");
            request.setAttribute("pid", pid);
            request.setAttribute("username", username);
            request.setAttribute("name", name);
            request.setAttribute("parentid", parentid);
            request.setAttribute("shopid", shopid);
            request.setAttribute("datastatus", datastatus);
            request.setAttribute("startTimeFrom", startTimeFrom);
            request.setAttribute("startTimeTo", startTimeTo);
            request.setAttribute("endTimeFrom", endTimeFrom);
            request.setAttribute("endTimeTo", endTimeTo);
            request.setAttribute("adminUserId", adminUserId);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("pGrade", pGrade);
            request.setAttribute("freeroutes", freeroutes);
            request.setAttribute("userNick", userNick);
            if (pUser != null) {
                request.setAttribute("pUserId", pUser.getId());
            }
            request.setAttribute("list", users);
            return modelAndView;
        }
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    // 下级账号
    @RequestMapping("/selectNextUsers")
    public ModelAndView selectNextUsers(HttpServletRequest request, String shareper,
                                        String id, String username, Integer datastatus, String name,
                                        Integer curPage, String shopid, String parentid, String startTimeFrom,
                                        String startTimeTo, String endTimeFrom, String endTimeTo) {
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }
        if (id == null) {
            if (request.getSession().getAttribute("id") != null) {
                id = (String) request.getSession().getAttribute("id");
            }
        }
        if (username == null) {
            if (request.getSession().getAttribute("username") != null) {
                username = (String) request.getSession().getAttribute("username");
            }
        }
        if (shopid == null) {
            if (request.getSession().getAttribute("shopid") != null) {
                shopid = (String) request.getSession().getAttribute("shopid");
            }
        }
        if (parentid == null) {
            if (request.getSession().getAttribute("parentid") != null) {
                parentid = (String) request.getSession().getAttribute("parentid");
            }
        }
        if (datastatus == null) {
            if (request.getSession().getAttribute("datastatus") != null) {
                datastatus = (Integer) request.getSession().getAttribute("datastatus");
            } else {
                datastatus = 0;
            }
        }
        if (parentid == null || parentid.equals("undefined")) {
            parentid = null;
        }
        if (shopid == null || shopid.equals("undefined")) {
            shopid = null;
        }

        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
//		Integer pGrade = 2;
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        String userNick = (String) request.getSession().getAttribute("userNick");
        List<Subscribers> users = null;
        // choose = 2 默认分页查询
        Integer choose = 2;
        if (adminUsergrade < 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("")
                    || shopid != null && !shopid.equals("") || parentid != null && !parentid.equals("")
                    || datastatus != 0 || startTimeFrom != null && !startTimeFrom.equals("")
                    && startTimeTo != null && !startTimeTo.equals("") || endTimeFrom != null
                    && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        if (adminUsergrade == 2) {
            if (id != null && !id.equals("") || username != null && !username.equals("") || datastatus != 0
                    || startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null
                    && !startTimeTo.equals("") || endTimeFrom != null && !endTimeFrom.equals("")
                    && endTimeTo != null && !endTimeTo.equals("")
                    || name != null && !name.equals("")) {
                choose = 1;
            }
        }

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();

        //oem查询或者商家查询
        String pName = null;
        String sName = null;
        String mobile = null;
        String sUserName = null;
        Boolean status = null;
        String sStartTimeFrom = null;
        String sStartTimeTo = null;
        String sEndTimeFrom = null;
        String sEndTimeTo = null;
        Users us = null;
        Page page = new Page();
        if (adminUsergrade == 0 || adminUsergrade == 1) {
            if (parentid != null && !parentid.equals("") && !parentid.equals("undefined")) {
//				us =usersService.selectByUsername(parentid);
//				pName = us.getId();
                pName = parentid;
            }
            if (shopid != null && !shopid.equals("") && !shopid.equals("undefined")) {
//				us =usersService.selectByUsername(shopid);
//				sName = us.getId();
                sName = shopid;
            }
        }
        if (username != null && !username.equals("")) {
            mobile = username;
        }
        if (name != null && !name.equals("")) {
            sUserName = name;
        }
        if (startTimeFrom != null && !startTimeFrom.equals("") && startTimeTo != null && !startTimeTo.equals("")) {
            sStartTimeFrom = startTimeFrom;
            sStartTimeTo = startTimeTo;
        }
        if (endTimeFrom != null && !endTimeFrom.equals("") && endTimeTo != null && !endTimeTo.equals("")) {
            sEndTimeFrom = endTimeFrom;
            sEndTimeTo = endTimeTo;
        }
        if (datastatus != null) {
            // 判断当前可用性
            switch (datastatus) {
                case 2:
                    status = false;
                    break;
                case 1:
                    status = true;
                    break;
                case 0:
                    break;
            }
        }
        page.setCurrentPageNo(curPage);
        if (adminUsergrade == 0) {
            page.setRecordTotal(subscribersService.countByAll(shareper, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByAll(page, shareper, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (adminUsergrade == 1) {
            page.setRecordTotal(subscribersService.countByParentid(adminUserId, shareper, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByParentid(page, adminUserId, shareper, mobile, sUserName, pName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }

        if (adminUsergrade == 2) {
            page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, shareper, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo));
            users = subscribersService.selectByShopidNotAll(page, adminUserId, shareper, mobile, sUserName, sName, status,
                    sStartTimeFrom, sStartTimeTo, sEndTimeFrom, sEndTimeTo);
        }
        if (choose == 2) {
            switch (adminUsergrade) {
                //  1. 判断是否是admin用户
                case 0:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByAll(shareper, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByAll(page, shareper, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是OEM用户
                case 1:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByParentid(adminUserId, shareper, null, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByParentid(page, adminUserId, shareper, null, null, null, null, null, null, null, null, null);
                    break;
                //  2. 判断是否是商家用户
                case 2:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countByShopidNotAll(adminUserId, shareper, null, null, null, null, null, null, null, null));
                    users = subscribersService.selectByShopidNotAll(page, adminUserId, shareper, null, null, null, null, null, null, null, null);
                    break;
            }
        }

        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

        if (users != null) {
            for (Subscribers u : users) {
                String pId = u.getParentid();
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());

                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());

                    if (parent.getId().equals("d34f8cb561bd48a992556f4faed45e2d")) {
                        if (parent.getFreeroute().equals("随便打")) {
                            u.setFreeroute("SBD0.25");
                        }
                    } else {
                        u.setFreeroute(parent.getFreeroute());
                    }
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

//				Subscribers sub = subscribersService.selectByPrimaryKey(u.getId()); // 用户信息
                // 计算用户已经消费积分
                float all = 0f; // 用户订单总返现积分
                float consume = withdrawalsService.countByAlready(u.getId(), 1, null); // 用户已经消费积分
                float ctIntegral = 0f; // 当前用户剩余总积分
                List<ShopAliOrder> shopAliOrder = shopAliOrderService.selectByAll(u.getId(), 1, 2); // 阿里订单集合
                // 判断用户是否有阿里订单 结算积分
                if (shopAliOrder != null && shopAliOrder.size() != 0) {
                    float aliSingle = 0f; // 单个阿里订单返现积分
                    // 商家积分计算类型为1 积分万分之五
                    if (usersService.selectByPrimaryKey(u.getShopid()).getIgtype() == 1) {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 结算金额
                            float jsmoney = s.getJsmoney().floatValue();
                            // 单个阿里订单已经返现积分 = 结算金额 * 天数 （天数 = 当前时间 - 创建时间）* 万分之五
                            aliSingle = jsmoney * Produce.differentDays(s.getClicktime(), Produce.getNowDate())
                                    * 0.0005f;
                            // 如果单个阿里订单返现积分大于结算金额 则积分 = 结算金额
                            if (aliSingle > jsmoney)
                                aliSingle = jsmoney;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                    // 类型为2 积分15%
                    else {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 单个订单返现积分 = 结算金额 * 15%
                            aliSingle = s.getJsmoney().floatValue() * 0.15f;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                }
                // ======未结算京东积分======
                // 判断用户是否有京东订单 结算积分
                // ======all+=京东积分======
                ctIntegral = all - consume; // 当前用户总积分 = 订单总积分 - 已经消费积分
                if (ctIntegral < 0f) {
                    ctIntegral = 0f;
                }
                // 积分
                u.setIntegral(ctIntegral);
                if (u.getIntegral() == null) {
                    u.setIntegral(0f);
                }
                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                DecimalFormat df = new DecimalFormat("#0.00");
                try {
                    // TODO 暂时配注
                    String result = VosHelper
                            .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                    if (result != null) {
                        VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                        System.out.println(v1.retCode);
                        if (v1.retCode == 0) {
                            String w = "";
                            w = df.format(v1.infoCustomers[0].getMoney());
//							w = v1.infoCustomers[0].getMoney().toString();
                            u.setAliaccount(w);
                        } else {
                            u.setAliaccount("暂无记录");
                        }
                    }
                } catch (Exception e) {
                    u.setAliaccount("暂无记录");
                }

                int shareSubs1 = rewardsService.countByAllLevel1(u.getId());
                int shareSubs2 = rewardsService.countByAllLevel2(u.getId());
                int shareSubs3 = rewardsService.countByAllLevel3(u.getId());
                int level1 = 0;
                if (shareSubs1 < 3){
                    level1 = 0;
                }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                    level1 = 1;
                }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                    level1 = 2;
                }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                    level1 = 3;
                }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                    level1 = 4;
                }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                    level1 = 5;
                }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                    level1 = 6;
                }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                    level1 = 7;
                }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                    level1 = 8;
                }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                    level1 = 9;
                }
                if (u.getCbonus1level() != 0 && u.getCbonus1level() > level1){
                    level1 = u.getCbonus1level();
                }
                if (level1 == 0){
                    u.setAchlevel1("无等级");
                }else {
                    u.setAchlevel1("T" + level1);
                }

                BigDecimal shareNum = payinfoesService.selectAllPerformance(u.getId(), 1).subtract(new BigDecimal(u.getAchievement1()));
                BigDecimal shareNum2 = payinfoesService.selectAllPerformance(u.getId(), 2).subtract(new BigDecimal(u.getAchievement2()));
                BigDecimal shareNum3 = payinfoesService.selectAllPerformance(u.getId(), 3).subtract(new BigDecimal(u.getAchievement3()));
                u.setAchlevel1Num(shareNum);
                u.setAchlevel2Num(shareNum2);
                u.setAchlevel3Num(shareNum3);

                float ig = 0f;
                List<Rewards> rewardsList = rewardsService.selectByPhase(pId, u.getId());
                if (rewardsList != null && rewardsList.size() > 0){
                    Rewards rewards = rewardsList.get(0);
                    ig = rewards.getIntegral().floatValue();
                }
                float igw = 0f;
                List<Rewards> igwList = rewardsService.selectByWithdraw(pId, u.getId());
                if (igwList != null && igwList.size() > 0){
                    Rewards rewards = igwList.get(0);
                    igw = rewards.getIntegral().floatValue();
                }
                float integral = rewardsService.countByIntegral(pId, u.getId())
                        + rewardsService.countByBonus(pId, u.getId())
                        + rewardsService.countByExtra(pId, u.getId())
                        + rewardsService.countBySelfShop(pId, u.getId())
                        + rewardsService.countByRefund(pId, u.getId())
                        - ig
                        - (withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f - igw);
                u.setIgrewardAll(integral);
                u.setWithdrawalsAll((withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f) - igw);
            }

            //费率
            FreeroutesExample freeroutesExample = new FreeroutesExample();
            freeroutesExample.setOrderByClause("CreateTime");
            freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
            List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);

            System.out.println();
            Users user = usersService.selectByPrimaryKey(adminUserId);
            Users pUser = usersService.selectByPrimaryKey(user.getParentid());

            CommExcel.subscribersList.clear();
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_xiajizhanghao");
            request.setAttribute("shareper", shareper);
            request.setAttribute("username", username);
            request.setAttribute("name", name);
            request.setAttribute("parentid", parentid);
            request.setAttribute("shopid", shopid);
            request.setAttribute("datastatus", datastatus);
            request.setAttribute("startTimeFrom", startTimeFrom);
            request.setAttribute("startTimeTo", startTimeTo);
            request.setAttribute("endTimeFrom", endTimeFrom);
            request.setAttribute("endTimeTo", endTimeTo);
            request.setAttribute("adminUserId", adminUserId);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("freeroutes", freeroutes);
            request.setAttribute("userNick", userNick);
            if (pUser != null) {
                request.setAttribute("pUserId", pUser.getId());
            }
            request.setAttribute("list", users);
            return modelAndView;
        }
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    // 分红账号
    @RequestMapping("/selectBonusUsers")
    public ModelAndView selectBonusUsers(HttpServletRequest request, Integer curPage, Integer level) {
        // 设置session缓存
        if (curPage == null) {
            if (request.getSession().getAttribute("curPage") != null) {
                curPage = (Integer) request.getSession().getAttribute("curPage");
            } else {
                curPage = 1;
            }
        }

        Integer adminUsergrade = (Integer) request.getSession().getAttribute("adminUsergrade");
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        String userNick = (String) request.getSession().getAttribute("userNick");
        List<Subscribers> users = null;
        // choose = 2 默认分页查询
        Integer choose = 2;
        if (adminUsergrade < 2) {
            if (level != null && !level.equals("")) {
                choose = 1;
            }
        }

        if (adminUsergrade == 2) {
            if (level != null && !level.equals("")) {
                choose = 1;
            }
        }

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();

        //oem查询或者商家查询
        Integer sLevel1 = null;
        Integer sLevel2 = null;
        Integer sLevel3 = null;
        Users us = null;
        Page page = new Page();
        if (level != null && !level.equals("")) {
            if (level <= 9){
                sLevel1 = level;
            }else if(level > 9 && level <= 15){
                sLevel2 = level;
            }else {
                sLevel3 = level;
            }
        }
        page.setCurrentPageNo(curPage);
        if (adminUsergrade == 0) {
            page.setRecordTotal(subscribersService.countBonusByAll(sLevel1, sLevel2, sLevel3));
            users = subscribersService.selectBonusByAll(page, sLevel1, sLevel2, sLevel3);
        }

        if (adminUsergrade == 1) {
            page.setRecordTotal(subscribersService.countBonusByParentid(adminUserId, sLevel1, sLevel2, sLevel3));
            users = subscribersService.selectBonusByParentid(page, adminUserId, sLevel1, sLevel2, sLevel3);
        }

        if (adminUsergrade == 2) {
            page.setRecordTotal(subscribersService.countBonusByShopidNotAll(adminUserId, sLevel1, sLevel2, sLevel3));
            users = subscribersService.selectBonusByShopidNotAll(page, adminUserId, sLevel1, sLevel2, sLevel3);
        }
        if (choose == 2) {
            switch (adminUsergrade) {
                //  1. 判断是否是admin用户
                case 0:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countBonusByAll(null, null, null));
                    users = subscribersService.selectBonusByAll(page, null, null, null);
                    break;
                //  2. 判断是否是OEM用户
                case 1:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countBonusByParentid(adminUserId,null, null, null));
                    users = subscribersService.selectBonusByParentid(page, adminUserId, null, null, null);
                    break;
                //  2. 判断是否是商家用户
                case 2:
                    page.setCurrentPageNo(curPage);
                    page.setRecordTotal(subscribersService.countBonusByShopidNotAll(adminUserId, null, null, null));
                    users = subscribersService.selectBonusByShopidNotAll(page, adminUserId, null, null, null);
                    break;
            }
        }

        request.setAttribute("totlenum", page.getRecordTotal()); // 分页
        request.setAttribute("curPage", page.getCurrentPageNo());// 当前页面传入session中

        if (users != null) {
            for (Subscribers u : users) {
                String pId = u.getParentid();
                u.setPassword(PasswordUtils.decodePWD(u.getPassword()));// 设置明文密码
                // 设置OEM以及所属商家的账户名
                Users parent = usersService.selectByPrimaryKey(u.getParentid());
                Users shop = usersService.selectByPrimaryKey(u.getShopid());

                if (parent != null && parent.getUsername() != null) {
                    u.setParentid(parent.getUsername());

                    if (parent.getId().equals("d34f8cb561bd48a992556f4faed45e2d")) {
                        if (parent.getFreeroute().equals("随便打")) {
                            u.setFreeroute("SBD0.25");
                        }
                    } else {
                        u.setFreeroute(parent.getFreeroute());
                    }
                } else {
                    u.setParentid("未知");
                    u.setFreeroute("未知");
                }

//				Subscribers sub = subscribersService.selectByPrimaryKey(u.getId()); // 用户信息
                // 计算用户已经消费积分
                float all = 0f; // 用户订单总返现积分
                float consume = withdrawalsService.countByAlready(u.getId(), 1, null); // 用户已经消费积分
                float ctIntegral = 0f; // 当前用户剩余总积分
                List<ShopAliOrder> shopAliOrder = shopAliOrderService.selectByAll(u.getId(), 1, 2); // 阿里订单集合
                // 判断用户是否有阿里订单 结算积分
                if (shopAliOrder != null && shopAliOrder.size() != 0) {
                    float aliSingle = 0f; // 单个阿里订单返现积分
                    // 商家积分计算类型为1 积分万分之五
                    if (usersService.selectByPrimaryKey(u.getShopid()).getIgtype() == 1) {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 结算金额
                            float jsmoney = s.getJsmoney().floatValue();
                            // 单个阿里订单已经返现积分 = 结算金额 * 天数 （天数 = 当前时间 - 创建时间）* 万分之五
                            aliSingle = jsmoney * Produce.differentDays(s.getClicktime(), Produce.getNowDate())
                                    * 0.0005f;
                            // 如果单个阿里订单返现积分大于结算金额 则积分 = 结算金额
                            if (aliSingle > jsmoney)
                                aliSingle = jsmoney;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                    // 类型为2 积分15%
                    else {
                        // 计算金额 转化积分
                        for (ShopAliOrder s : shopAliOrder) {
                            // 单个订单返现积分 = 结算金额 * 15%
                            aliSingle = s.getJsmoney().floatValue() * 0.15f;
                            all += aliSingle; // 订单总返现积分
                        }
                    }
                }
                // ======未结算京东积分======
                // 判断用户是否有京东订单 结算积分
                // ======all+=京东积分======
                ctIntegral = all - consume; // 当前用户总积分 = 订单总积分 - 已经消费积分
                if (ctIntegral < 0f) {
                    ctIntegral = 0f;
                }
                // 积分
                u.setIntegral(ctIntegral);
                if (u.getIntegral() == null) {
                    u.setIntegral(0f);
                }
                if (shop != null && shop.getUsername() != null) {
                    u.setShopid(shop.getUsername());
                } else {
                    u.setShopid("未知");
                }
                if (u.getUsername() == null) {
                    u.setUsername("未上传姓名");
                }
                DecimalFormat df = new DecimalFormat("#0.00");
                try {
                    // TODO 暂时配注
                    String result = VosHelper
                            .GetVosAccount("{accounts:['" + parent.getAgentprefix() + u.getMobile() + "']}");
                    if (result != null) {
                        VosModelList v1 = GsonUtil.getObject(result, VosModelList.class);
                        System.out.println(v1.retCode);
                        if (v1.retCode == 0) {
                            String w = "";
                            w = df.format(v1.infoCustomers[0].getMoney());
//							w = v1.infoCustomers[0].getMoney().toString();
                            u.setAliaccount(w);
                        } else {
                            u.setAliaccount("暂无记录");
                        }
                    }
                } catch (Exception e) {
                    u.setAliaccount("暂无记录");
                }

                int shareSubs1 = rewardsService.countByAllLevel1(u.getId());
                int shareSubs2 = rewardsService.countByAllLevel2(u.getId());
                int shareSubs3 = rewardsService.countByAllLevel3(u.getId());
                int level1 = 0;
                if (shareSubs1 < 3){
                    level1 = 0;
                }else if (shareSubs1 >= 3 && shareSubs1 < 8){
                    level1 = 1;
                }else if (shareSubs1 >= 8 && shareSubs1 < 15){
                    level1 = 2;
                }else if (shareSubs1 >= 15 && shareSubs1 < 20){
                    level1 = 3;
                }else if (shareSubs1 >= 20 && shareSubs1 < 30 && shareSubs2 >= 60 && shareSubs2 < 120){
                    level1 = 4;
                }else if (shareSubs1 >= 30 && shareSubs1 < 40 && shareSubs2 >= 120 && shareSubs2 < 180){
                    level1 = 5;
                }else if (shareSubs1 >= 40 && shareSubs1 < 60 && shareSubs2 >= 180 && shareSubs2 < 300){
                    level1 = 6;
                }else if (shareSubs1 >= 60 && shareSubs1 < 80 && shareSubs2 >= 300 && shareSubs2 < 450 && shareSubs3 >= 900 && shareSubs3 < 1350){
                    level1 = 7;
                }else if (shareSubs1 >= 80 && shareSubs1 < 100 &&shareSubs2 >= 450 && shareSubs2 < 600 && shareSubs3 >= 1350 && shareSubs3 < 1800){
                    level1 = 8;
                }else if (shareSubs1 >= 100 && shareSubs2 >= 600 && shareSubs3 >= 1800){
                    level1 = 9;
                }
                if (u.getCbonus1level() != 0 && u.getCbonus1level() > level1){
                    level1 = u.getCbonus1level();
                }
                if (level1 == 0){
                    u.setAchlevel1("无等级");
                }else {
                    u.setAchlevel1("T" + level1);
                }

                BigDecimal shareNum = payinfoesService.selectAllPerformance(u.getId(), 1).subtract(new BigDecimal(u.getAchievement1()));
                BigDecimal shareNum2 = payinfoesService.selectAllPerformance(u.getId(), 2).subtract(new BigDecimal(u.getAchievement2()));
                BigDecimal shareNum3 = payinfoesService.selectAllPerformance(u.getId(), 3).subtract(new BigDecimal(u.getAchievement3()));
                u.setAchlevel1Num(shareNum);
                u.setAchlevel2Num(shareNum2);
                u.setAchlevel3Num(shareNum3);

                float ig = 0f;
                List<Rewards> rewardsList = rewardsService.selectByPhase(pId, u.getId());
                if (rewardsList != null && rewardsList.size() > 0){
                    Rewards rewards = rewardsList.get(0);
                    ig = rewards.getIntegral().floatValue();
                }
                float igw = 0f;
                List<Rewards> igwList = rewardsService.selectByWithdraw(pId, u.getId());
                if (igwList != null && igwList.size() > 0){
                    Rewards rewards = igwList.get(0);
                    igw = rewards.getIntegral().floatValue();
                }
                float integral = rewardsService.countByIntegral(pId, u.getId())
                        + rewardsService.countByBonus(pId, u.getId())
                        + rewardsService.countByExtra(pId, u.getId())
                        + rewardsService.countBySelfShop(pId, u.getId())
                        + rewardsService.countByRefund(pId, u.getId())
                        - ig
                        - (withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f - igw);
                u.setIgrewardAll(integral);
                u.setWithdrawalsAll((withdrawalsService.countByAlready(u.getId(), 2, 1)/0.92f) - igw);
            }

            //费率
            FreeroutesExample freeroutesExample = new FreeroutesExample();
            freeroutesExample.setOrderByClause("CreateTime");
            freeroutesExample.getOredCriteria().add(freeroutesExample.createCriteria().andDatastatusEqualTo(true));
            List<Freeroutes> freeroutes = freeroutesService.selectByExample(freeroutesExample);

            Users user = usersService.selectByPrimaryKey(adminUserId);
            Users pUser = usersService.selectByPrimaryKey(user.getParentid());

            CommExcel.subscribersList.clear();
            // 设置页面进行跳转
            modelAndView.setViewName("jsp/content_fenhongzhanghao");
            request.setAttribute("shareper", level);
            request.setAttribute("adminUserId", adminUserId);
            request.setAttribute("adminUsergrade", adminUsergrade);
            request.setAttribute("freeroutes", freeroutes);
            request.setAttribute("userNick", userNick);
            if (pUser != null) {
                request.setAttribute("pUserId", pUser.getId());
            }
            request.setAttribute("list", users);
            return modelAndView;
        }
        modelAndView.setViewName("jsp/datanotfound");
        return modelAndView;
    }

    @RequestMapping("/allSubscribers")
    private @ResponseBody List<Object> allSubscribers(HttpServletRequest request, HttpServletResponse response,
                                                      String parentid, Integer isnull) {
        List<Object> subList = new ArrayList<>();
        Map<String, Object> subMap= new HashMap<>();

//        List<Subscribers> allSubscribers = subscribersService.selectAllSub(parentid, isnull);
        List<Subscribers> allSubscribers = subscribersService.selectBySub(null, parentid);
        int i = 0;
        if (allSubscribers != null && allSubscribers.size() > 0){
            for (Subscribers subscribers : allSubscribers){
                subMap = new HashMap<>();
                subMap.put("id", subscribers.getId());
                subMap.put("title", subscribers.getUsername() == null ? subscribers.getMobile() : subscribers.getUsername() + "_" + subscribers.getMobile());
                subMap.put("pid", subscribers.getShareper());

                subList.add(subMap);
            }
        }

        return subList == null && subList.size() < 1 ? null : subList;
    }

    @RequestMapping("/subRelation")
    private @ResponseBody List<Object> subRelation(HttpServletRequest request, HttpServletResponse response,
                                                      String userId, Integer type) {
        List<Object> subList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        if (type == 1){
            do {
                try {
                    Subscribers subscribers = subscribersService.selectByPrimaryKey(userId);
                    if (subscribers != null){
                        map = new HashMap<>();
                        map.put("id", subscribers.getId());
                        map.put("title", subscribers.getMobile());
                        map.put("open","true");
                        map.put("pId", subscribers.getShareper());
                        subList.add(map);
                        if (subscribers.getShareper() != null && !subscribers.getShareper().equals("")){
                            userId = subscribers.getShareper();
                        }else{
                            break;
                        }
                    }else{
                        break;
                    }
                }catch (Exception e){
                    System.out.println(e);
                    break;
                }
            }while (true);
        }else{
            List<Subscribers> subscribersList = subscribersService.selectBySharePer(userId);
            for (Subscribers sub : subscribersList){
                map = new HashMap<>();
                map.put("id", sub.getId());
                map.put("title", sub.getMobile());
                map.put("open","true");
                subList.add(map);
            }
        }

        return subList == null && subList.size() < 1 ? null : subList;
    }

    @RequestMapping("/addressBook")
    private void addressBook(HttpServletRequest request, HttpServletResponse response, String userId) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        List<AddressBook> addressBook = addressBookService.selectByUserID(userId);
        if (!addressBook.isEmpty() && !addressBook.get(0).getAddressbookinfo().isEmpty()){
            out.print(addressBook.get(0).getAddressbookinfo());
        }else {
            out.print("");
        }
    }

    //导入用户
    @RequestMapping("/subscribersInfo")
    private void subscribersInfo(HttpServletRequest request, HttpServletResponse response, String file) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
//    	ModelAndView modelAndView = new ModelAndView();

        readExcel(request, response, file);

        for (Subscribers s : CommExcel.subscribersList) {
            if (s.getParentid() == null && s.getParentid().equals("")) {
                out.print(s.getMobile() + "的代理商信息为空");
                return;
            }
            if (s.getShopid() == null && s.getShopid().equals("")) {
                out.print(s.getMobile() + "的商家信息为空");
                return;
            }

            List<Users> pUsers = usersService.selectByUserName(s.getParentid());
            List<Users> sUsers = usersService.selectByUserName(s.getShopid());

            if (pUsers == null) {
                out.print(s.getMobile() + "的代理商信息未查询到");
                return;
            }

            if (sUsers == null) {
                out.print(s.getMobile() + "的商家信息未查询到");
                return;
            }

            if (sUsers.get(0).getRole() == 1) {
                if (!sUsers.get(0).getId().equals(pUsers.get(0).getId())) {
                    out.print(s.getMobile() + "的商家不能为其他代理商");
                    return;
                }
            }

            if (sUsers.get(0).getRole() == 2) {
                if (!sUsers.get(0).getParentid().equals(pUsers.get(0).getId())) {
                    out.print(s.getMobile() + "的商家与代理商对应有误");
                    return;
                }
            }

            List<String> subscribersSId = subscribersService.selectByMobileAndShopId(s.getMobile(), sUsers.get(0).getId());
            if (subscribersSId != null && subscribersSId.size() > 0) {
                out.print(s.getMobile() + "在商家" + sUsers.get(0).getUsername() + "下以存在");
                return;
            }

            List<String> subscribersPId = subscribersService.selectByMobileAndParentId(s.getMobile(), pUsers.get(0).getId());
            if (subscribersPId != null && subscribersPId.size() > 0) {
                out.print(s.getMobile() + "在代理商" + pUsers.get(0).getUsername() + "下以存在");
                return;
            }
        }

        insertSubscribers(request, response);

    }

    @RequestMapping("/insertSubscribers")
    private void insertSubscribers(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String adminId = (String) request.getSession().getAttribute("adminUserId");

        //核对数据库有 Excel没有的

        Subscribers subscribers = null;

        for (Subscribers s : CommExcel.subscribersList) {
            List<Users> pUsers = null;
            if (s.getParentid() == null) {
                pUsers = usersService.selectByUserName(s.getParentid());
            } else {
                Users pu = usersService.selectByPrimaryKey(adminId);
                pUsers = usersService.selectByUserName(pu.getUsername());
            }
            List<Users> sUsers = null;
            if (s.getShopid() == null) {
                sUsers = usersService.selectByUserName(s.getShopid());
            } else {
                Users su = usersService.selectByPrimaryKey(adminId);
                sUsers = usersService.selectByUserName(su.getUsername());
            }

            subscribers = new Subscribers(Produce.getUUID(), PasswordUtils.toPWD("123456"), Produce.getNowDate(), Produce.getNowDate(), null, 4,
                    true, s.getMobile(), pUsers.get(0).getId(), Produce.plusDay(365, Produce.getNowDate()), null, 7, sUsers.get(0).getId(),
                    "1", 0f, null, false, 0, (new SimpleDateFormat("yyyy-MM-dd")).format(Produce.plusDay(365, Produce.getNowDate())),
                    null, "0", null, null, null, false, false, false);
            int resultCode = subscribersService.insertSelective(subscribers);

            if (resultCode != 1) {
                out.print(s.getMobile() + "导入时出错");
                return;
            }
        }
        out.print("导入成功");
    }


    public void readExcel(HttpServletRequest request, HttpServletResponse response, String file) throws Exception {

        PrintWriter out = response.getWriter();
        if (file == null || CommExcel.EMPTY.equals(file)) {
            out.println("请传入正确的Excel文件");
            return;
        } else {
            String postfix = getPostfix(file);
            if (!CommExcel.EMPTY.equals(postfix)) {
                if (CommExcel.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    readXls(request, response, file);
                } else if (CommExcel.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    readXlsx(request, response, file);
                }
            } else {
                System.out.println(file + CommExcel.NOT_EXCEL_FILE);
            }
        }
    }

    /**
     * 读取 Excel 2010
     *
     * @param file
     * @return
     * @throws IOException
     */
    public void readXlsx(HttpServletRequest request, HttpServletResponse response, String file) throws Exception {
        System.out.println(CommExcel.PROCESSING + file);
        InputStream is = new FileInputStream(file);
        @SuppressWarnings("resource")
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        Subscribers subscribers = null;
        // 读取表格
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            // 读取行
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                    subscribers = new Subscribers();
                    DecimalFormat df = new DecimalFormat("#");
                    Double mobile = xssfRow.getCell(0).getNumericCellValue();
                    XSSFCell parentid = xssfRow.getCell(1);
                    XSSFCell shopid = xssfRow.getCell(2);

                    subscribers.setMobile(df.format(mobile));
                    subscribers.setParentid(getXValue(parentid));
                    subscribers.setShopid(getXValue(shopid));

                    CommExcel.subscribersList.add(subscribers);
                }
            }
        }
    }

    /**
     * 读取 Excel 2003-2007
     *
     * @param file
     * @return
     * @throws IOException
     */
    public void readXls(HttpServletRequest request, HttpServletResponse response, String file) throws IOException {
        System.out.println(CommExcel.PROCESSING + file);
        PrintWriter out = response.getWriter();
        InputStream is = new FileInputStream(file);
        @SuppressWarnings("resource")
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        Subscribers subscribers = null;
        // 读取表格
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 读取行
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    subscribers = new Subscribers();
                    DecimalFormat df = new DecimalFormat("#");
                    Double mobile = hssfRow.getCell(0).getNumericCellValue();
                    HSSFCell parentid = hssfRow.getCell(1);
                    HSSFCell shopid = hssfRow.getCell(2);

                    subscribers.setMobile(df.format(mobile));
                    subscribers.setParentid(getHValue(parentid));
                    subscribers.setShopid(getHValue(shopid));


                    CommExcel.subscribersList.add(subscribers);
                }
            }
        }
    }

    //Excal 2007-2010 取值
    @SuppressWarnings({"static-access", "deprecation"})
    private String getXValue(XSSFCell xssfRow) {
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfRow.getBooleanCellValue());
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            return String.valueOf(xssfRow.getNumericCellValue());
        } else {
            return String.valueOf(xssfRow.getStringCellValue());
        }
    }

    //Excal 2003 取值
    @SuppressWarnings({"static-access", "deprecation"})
    private String getHValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }


    //判断Excel 2003 或者2007-2010
    public static String getPostfix(String file) {
        if (file == null || CommExcel.EMPTY.equals(file)) {
            return CommExcel.EMPTY;
        }
        if (file.contains(CommExcel.POINT)) {
            return file.substring(file.lastIndexOf(CommExcel.POINT) + 1);
        }
        return CommExcel.EMPTY;
    }
}
